package com.satan.fmmall.websocket;

import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName WebSocketServer
 * @Description TODO
 * @date 2022/4/19 19:59
 * @Version 1.0
 */
@Component
@ServerEndpoint("/websocket/{orderId}")
public class WebSocketServer {
    private static ConcurrentHashMap sessionMap = new ConcurrentHashMap();

    @OnOpen
    public void open(@PathParam("orderId") String orderId, Session session) {
        System.out.println("open");
        sessionMap.put(orderId, session);
    }

    @OnClose    //关闭连接
    public void close(@PathParam("orderId") String orderId) {
        sessionMap.remove(orderId);
    }

    public static void sendMessage(String orderId,String msg){
        Session session = (Session) sessionMap.get(orderId);
        if(session != null){
            session.getAsyncRemote().sendText(msg);
        }
    }

}
